package com.chapter14.list_;

/**
 * @author 宋鑫宇
 * @version 1.0
 * LinkedList的使用
 */
public class LinkedList_ {
    public static void main(String[] args) {
        //模拟简单的双向链表
        Node mary = new Node("mary");
        Node tom = new Node("tom");
        Node jack = new Node("jack");
        //链接三个节点，形成双向链表
        mary.next = tom;
        tom.next = jack;
        jack.pre = tom;
        tom.pre = mary;
        Node first = mary;//让first引用指向mary,就是双向链表的头结点
        Node last = jack;//让last引用指向jack,就是双向链表的尾节点

        //演示从头到尾进行遍历
        while (first != null) {
            System.out.println(first);
            first = first.next;
        }
        System.out.println("=========================");
        //从尾到头进行遍历
        while (last != null){
            System.out.println(last);
            last = last.pre;
        }
        System.out.println("===========================");
        //演示链表添加数据和删除数据的实用性
        //添加
        //1.先创建一个Node节点，name就是smith
        Node smith = new Node("smith");
        tom.next = smith;
        smith.next = jack;
        jack.pre = smith;
        smith.pre = tom;
        //遍历链表中的对象
        first = mary;//让first再次指向第一个对象
        while (first != null) {
            System.out.println(first);
            first = first.next;
        }
    }
}

//定义一个Node类，表示双向链表的节点
class Node{
    public Object item;//存放真正的数据
    public Node next;//指向后一个节点
    public Node pre;//指向前一个节点

    public Node(Object name){
        this.item = name;
    }


    public String toString() {
        return "Node{" +
                "item=" + item +
                '}';
    }
}